<template>
  <div class="login-page">
    <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="100px" class="login-form" size="large">
      <h1 style="color:#606266; text-align: center;">管理平台</h1>
      <el-form-item label-width="0px" prop="username" class="form-item">
        <el-input v-model="loginForm.username" placeholder="请输入账户" :prefix-icon="User"></el-input>
      </el-form-item>
      <el-form-item label-width="0px" prop="password" class="form-item">
        <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" show-password
          :prefix-icon="Lock"></el-input>
      </el-form-item>
      <el-form-item label-width="0px" class="form-item">
        <div style="display: flex; justify-content: flex-end; width: 100%;">
          <el-button type="primary" @click="submitForm" style="width: 100%;">登录</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ajax } from '@/api/ajax';
import api from '@/api/index'
import { useStore } from 'vuex';
import { User, Lock } from '@element-plus/icons-vue';
import {useRouter } from 'vue-router'

const loginFormRef = ref<FormInstance>();
const router = useRouter();

const loginForm = reactive({
  username: '',
  password: ''
});

const rules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '字符个数在 3 到 20之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 1, max: 20, message: '字符个数在 1 到 20之间', trigger: 'blur' }
  ]
};

const store = useStore();
const submitForm = async () => {
  if (!loginFormRef.value) return;
  await loginFormRef.value.validate((valid) => {
    if (valid) {
      console.log("denglu: ", loginForm)
      ajax({
        url: api.loginApi.login,
        method: 'post',
        params: loginForm
      }).then((res: any) => {
        if (res.code === '0000') {
          debugger;
          store.commit('user/setToken', res.data.token);
          store.commit('user/setIsLogin', true);
          store.commit('user/setCurrentUser', res.data)
          router.push("/home");
        }
      });
    }
  });
};
</script>

<style scoped>
.login-page {
  height: 100%;
  background: linear-gradient(180deg, #ADD8E6, #87CEFA);
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.login-form {
  width: 350px;
  margin: 0 100px;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  background-color: aliceblue;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.form-item {
  margin-bottom: 38px;
}
</style>